import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../providers/provider_container.dart';
import '../intent/game_state.dart';
import '../model/game_viewmodel.dart';

class GamePage extends ConsumerStatefulWidget {
  @override
  ConsumerState<ConsumerStatefulWidget> createState() {
    return _GamePageState();
  }
}

class _GamePageState extends ConsumerState<GamePage> {
  GameViewModel get viewModel => ref.read(gameViewModelProvider.notifier);

  @override
  Widget build(BuildContext context) {
    final GameState state = ref.watch(gameViewModelProvider);
    return Scaffold(
      body: SafeArea(
        child: Stack(
          children: [
            Image.asset(
              'assets/images/machine1_bg.png',
              width: MediaQuery.of(context).size.width,
              fit: BoxFit.fitWidth,
              errorBuilder: (context, error, stackTrace) {
                return Text('图片加载失败');
              },
            ),

            Positioned(
              top: 100.w,
              left: 42.w,
              child: Row(children: buildScore(state.bonusWin, state.numberList)),
            ),

            Positioned(
              top: 100.w,
              right: 43.w,
              child: Row(children: buildScore(state.credit, state.numberList)),
            ),

            ...state.runList.map((runItem) {
              return Positioned(
                top: runItem.top.w,
                left: runItem.left.w,
                child: Image.asset(
                  runItem.imgRes,
                  width: 73.w,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Text('图片加载失败');
                  },
                ),
              );
            }),

            Positioned(
              top: 320,
              left: 0,
              right: 0,
              child: Center(
                child: Container(
                  child: Stack(
                    children: [
                      Image.asset(
                        'assets/images/middle_bg.png',
                        width: 76.w,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Text('图片加载失败');
                        },
                      ),

                      Positioned(
                        left: 0,
                        right: 0,
                        top: 0,
                        bottom: 0,
                        child: Container(
                          margin: EdgeInsets.only(bottom: 1.w),
                          child: Center(child: SizeNumber()),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),

            Positioned(
              top: 561.w,
              child: Container(
                width: MediaQuery.of(context).size.width,
                padding: EdgeInsets.only(left: 10.w, right: 10.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    CustomImageButton(
                      normalImage: state.consoleList[0].normalImage,
                      pressedImage: state.consoleList[0].pressedImage,
                      disabledImage: state.consoleList[0].disabledImage,
                      width: state.consoleList[0].width.w,
                      enabled: state.consoleList[0].enabled,
                      onPressed: () {
                        viewModel.clickLeftButton(context);
                      },
                    ),
                    CustomImageButton(
                      normalImage: state.consoleList[1].normalImage,
                      pressedImage: state.consoleList[1].pressedImage,
                      disabledImage: state.consoleList[1].disabledImage,
                      width: state.consoleList[1].width.w,
                      enabled: state.consoleList[1].enabled,
                      onPressed: () {
                        viewModel.clickRightButton(context);
                      },
                      onLongPress: () {
                        viewModel.clickLongRightButton(context);
                      },
                    ),
                    CustomImageButton(
                      normalImage: state.consoleList[2].normalImage,
                      pressedImage: state.consoleList[2].pressedImage,
                      disabledImage: state.consoleList[2].disabledImage,
                      width: state.consoleList[2].width.w,
                      enabled: state.consoleList[2].enabled,
                      onPressed: () {
                        viewModel.clickSmallButton(context);
                      },
                    ),
                    CustomImageButton(
                      normalImage: state.consoleList[3].normalImage,
                      pressedImage: state.consoleList[3].pressedImage,
                      disabledImage: state.consoleList[3].disabledImage,
                      width: state.consoleList[3].width.w,
                      enabled: state.consoleList[3].enabled,
                      onPressed: () {
                        viewModel.clickBigButton(context);
                      },
                    ),
                    CustomImageButton(
                      normalImage: state.consoleList[4].normalImage,
                      pressedImage: state.consoleList[4].pressedImage,
                      disabledImage: state.consoleList[4].disabledImage,
                      width: state.consoleList[4].width.w,
                      enabled: state.consoleList[4].enabled,
                      onPressed: () {
                        viewModel.clickGoButton(context);
                      },
                    ),
                  ],
                ),
              ),
            ),

            Positioned(
              top: 627.w,
              left: 71.w,
              child: Container(
                child: Row(
                  children: [
                    Image.asset(
                      width: 165.w,
                      height: 38.w,
                      'assets/images/fen_left.png',
                      fit: BoxFit.fill,
                      errorBuilder: (context, error, stackTrace) {
                        return Text('图片加载失败');
                      },
                    ),
                    SizedBox(width: 6.w),
                    Image.asset(
                      width: 165.w,
                      height: 38.w,
                      'assets/images/fen_right.png',
                      fit: BoxFit.fill,
                      errorBuilder: (context, error, stackTrace) {
                        return Text('图片加载失败');
                      },
                    ),
                  ],
                ),
              ),
            ),

            Positioned(
              top: 669.w,
              child: Container(
                padding: EdgeInsets.only(left: 6.w, right: 5.w),
                width: MediaQuery.of(context).size.width,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: state.buttonList.asMap().entries.map((entry) {
                    return BetNumber(entry.key);
                  }).toList(),
                ),
              ),
            ),

            Positioned(
              top: 707.w,
              child: Container(
                padding: EdgeInsets.only(left: 3.w, right: 3.w),
                width: MediaQuery.of(context).size.width,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: state.buttonList.asMap().entries.map((entry) {
                    return CustomImageButton(
                      normalImage: state.buttonList[entry.key].normalImage,
                      pressedImage: state.buttonList[entry.key].pressedImage,
                      disabledImage: state.buttonList[entry.key].disabledImage,
                      width: state.buttonList[entry.key].width.w,
                      enabled: state.buttonList[entry.key].enabled,
                      onPressed: () {
                        viewModel.clickButton(context, entry.key);
                      },
                      onLongPress: () {
                        print('长按点击事件');
                      },
                    );
                  }).toList(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> buildScore(int number, List<String> numberList) {
    List<Widget> widgets = [];
    int length = number.abs().toString().length;
    String str = number.abs().toString();
    if (length < 8) {
      for (int i = 0; i < 8 - length; i++) {
        widgets.add(SizedBox(width: 22.w));
      }
    }
    for (int i = 0; i < length; i++) {
      widgets.add(
        Image.asset(
          numberList[int.parse(str[i])],
          width: 22.w,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Text('图片加载失败');
          },
        ),
      );
    }
    return widgets;
  }
}

class TopScore extends ConsumerWidget {
  final int index;

  TopScore(this.index);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final GameState state = ref.watch(gameViewModelProvider);
    final GameViewModel viewModel = ref.read(gameViewModelProvider.notifier);
    return Image.asset(
      'assets/images/top_8.png',
      width: 22.w,
      fit: BoxFit.cover,
      errorBuilder: (context, error, stackTrace) {
        return Text('图片加载失败');
      },
    );
  }
}

class SizeNumber extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final GameState state = ref.watch(gameViewModelProvider);
    List<int> digits = state.sizeNumber.toString().split('').map((e) => int.parse(e)).toList();
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (state.sizeNumber < 10)
          SizedBox(width: 22.w)
        else
          Image.asset(
            state.numberList[digits.first],
            width: 22.w,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              return Text('图片加载失败');
            },
          ),
        SizedBox(width: 4.w),
        Image.asset(
          state.numberList[digits.last],
          width: 22.w,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Text('图片加载失败');
          },
        ),
      ],
    );
  }
}

class BetNumber extends ConsumerWidget {
  final int index;

  BetNumber(this.index);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final GameState state = ref.watch(gameViewModelProvider);
    final GameViewModel viewModel = ref.read(gameViewModelProvider.notifier);
    return Row(
      children: [
        state.betList[index] < 10
            ? SizedBox(width: 18.w)
            : Image.asset(
                width: 18.w,
                viewModel.getResForNumberStart(state.betList[index]),
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Text('图片加载失败');
                },
              ),
        SizedBox(width: 1.w),
        Image.asset(
          width: 18.w,
          viewModel.getResForNumberEnd(state.betList[index]),
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Text('图片加载失败');
          },
        ),
      ],
    );
  }
}

class CustomImageButton extends StatefulWidget {
  final String normalImage;
  final String pressedImage;
  final String disabledImage;
  final VoidCallback? onPressed;
  final VoidCallback? onLongPress;
  final bool enabled;
  final double width;

  const CustomImageButton({Key? key, required this.normalImage, required this.pressedImage, required this.disabledImage, required this.width, this.onPressed, this.onLongPress, this.enabled = true}) : super(key: key);

  @override
  _CustomImageButtonState createState() => _CustomImageButtonState();
}

class _CustomImageButtonState extends State<CustomImageButton> {
  bool _isPressed = false;

  @override
  Widget build(BuildContext context) {
    bool isDisabled = !widget.enabled || widget.onPressed == null;
    String currentImage = isDisabled
        ? widget.disabledImage
        : _isPressed
        ? widget.pressedImage
        : widget.normalImage;
    return GestureDetector(
      // 当用户按下按钮时触发，如果按钮可用则设置_pressed状态为true
      onTapDown: isDisabled ? null : (_) => setState(() => _isPressed = true),
      // 当用户抬起手指时触发，如果按钮可用则设置_pressed状态为false
      onTapUp: isDisabled ? null : (_) => setState(() => _isPressed = false),
      // 当用户取消点击操作时触发，如果按钮可用则设置_pressed状态为false
      onTapCancel: isDisabled ? null : () => setState(() => _isPressed = false),
      // 当用户单击按钮时触发，如果按钮可用则执行onPressed回调
      onTap: isDisabled ? null : widget.onPressed,
      // 当用户长按按钮时触发，如果按钮可用则执行onLongPress回调
      onLongPress: isDisabled ? null : widget.onLongPress,
      // 显示当前状态对应的图片，根据按钮是否被按下或禁用来切换图片
      child: Image.asset(currentImage, width: widget.width, fit: BoxFit.cover),
    );
  }
}
